package com.lt.flashcard.view;

import java.util.Date;

import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.util.Clients;

import com.lt.flashcard.Utility;
import com.lt.flashcard.model.entity.User;
import com.lt.flashcard.model.service.AAService;
import com.lt.flashcard.model.service.Repository;
import com.lt.flashcard.model.service.UserService;

public class ActivationCtrl extends SelectorComposer<Component> {

	private static final long serialVersionUID = 1L;
	
	@Override
	public void doAfterCompose(Component comp) throws Exception {
		super.doAfterCompose(comp);
	
		UserService srv  = Repository.getInstance().getUserService();
		AAService asrv  = Repository.getInstance().getAAService();
		String code = Executions.getCurrent().getParameter("code");
		if(Utility.isLogin() || Utility.isEmptyString(code)) {
			Utility.redirect("/wordlist.zul", true);
			return;
		}
		
		Date date = new Date();
		try{
			User u = srv.findByActivationCode(code);
			if(u != null){
				if(u.getExpiredate().getTime() < date.getTime()){
					Clients.evalJavaScript("showNotice('The code is expired')");
				}
				else{
					u.setBlock(0);
					u.setActivation("");
					u.setExpiredate(null);
					srv.save(u);
					
					asrv.doLogin(u.getUsername(), u.getPassword(), false, false);
					
					Utility.redirect("thanksregister.zul", true);
				}
			}
			else{
				Clients.evalJavaScript("showNotice('Unknow activation code'");
			}
		} catch (Exception e) {
			Clients.evalJavaScript("showNotice('" + e.toString() + "')");
		}
	}
}
